<!DOCTYPE html><html class="theme-next gemini use-motion" lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta name="theme-color" content="#222"><script src="/MyBlog/lib/pace/pace.min.js?v=1.0.2"></script><link href="/MyBlog/lib/pace/pace-theme-loading-bar.min.css?v=1.0.2" rel="stylesheet"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/MyBlog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"><link href="/MyBlog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/MyBlog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css"><link rel="apple-touch-icon" sizes="180x180" href="/MyBlog/images/apple-touch-icon-next.png?v=5.1.4"><link rel="icon" type="image/png" sizes="32x32" href="/MyBlog/images/bitbug_favicon.ico?v=5.1.4"><link rel="icon" type="image/png" sizes="16x16" href="/MyBlog/images/bitbug_favicon16.ico?v=5.1.4"><link rel="mask-icon" href="/MyBlog/images/logo.svg?v=5.1.4" color="#222"><meta name="keywords" content="Vue,"><meta name="description" content="路由后端路由概念:根据不同的用户URL请求，返回不同的内容本质:URL请求地址与服务器资源之间的对应关系前端路由概念:根据不同的用户事件，显示不同的页面内容本质:用户事件与事件处理函数之间的对应关系Vue Router&amp;emsp;&amp;emsp;vue Router(官网: https:&#x2F;&#x2F;router.vuejs.org&#x2F;zh&#x2F; )是Vue.js官方的路由管理器。"><meta property="og:type" content="article"><meta property="og:title" content="Vue中的路由"><meta property="og:url" content="https://gitee.com/yang_yu_xiang/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/index.html"><meta property="og:site_name" content="Yang&#39;s Blog"><meta property="og:description" content="路由后端路由概念:根据不同的用户URL请求，返回不同的内容本质:URL请求地址与服务器资源之间的对应关系前端路由概念:根据不同的用户事件，显示不同的页面内容本质:用户事件与事件处理函数之间的对应关系Vue Router&amp;emsp;&amp;emsp;vue Router(官网: https:&#x2F;&#x2F;router.vuejs.org&#x2F;zh&#x2F; )是Vue.js官方的路由管理器。"><meta property="og:image" content="https://gitee.com/yang_yu_xiang/BlogImages/raw/master/img/%E5%B5%8C%E5%A5%97%E8%B7%AF%E7%94%B1.png"><meta property="article:published_time" content="2020-07-28T08:16:41.000Z"><meta property="article:modified_time" content="2020-11-19T07:41:11.075Z"><meta property="article:author" content="杨雨翔"><meta property="article:tag" content="Vue"><meta name="twitter:card" content="summary"><meta name="twitter:image" content="https://gitee.com/yang_yu_xiang/BlogImages/raw/master/img/%E5%B5%8C%E5%A5%97%E8%B7%AF%E7%94%B1.png"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/MyBlog/",scheme:"Gemini",version:"5.1.4",sidebar:{position:"left",display:"post",offset:12,b2t:!1,scrollpercent:!0,onmobile:!0},fancybox:!0,tabs:!0,motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},duoshuo:{userId:"0",author:"博主"},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><link rel="canonical" href="https://gitee.com/yang_yu_xiang/MyBlog/2020/07/28/Vue中的路由/"><title>Vue中的路由 | Yang's Blog</title><meta name="generator" content="Hexo 4.2.1"></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><a href="https://gitee.com/yang_yu_xiang" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/MyBlog/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">Yang's Blog</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle">永远年轻 永远热泪盈眶</p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/MyBlog/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-tags"><a href="/MyBlog/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-categories"><a href="/MyBlog/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-archives"><a href="/MyBlog/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li><li class="menu-item menu-item-search"><a href="javascript:;" class="popup-trigger"><i class="menu-item-icon fa fa-search fa-fw"></i><br>搜索</a></li></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://gitee.com/yang_yu_xiang/MyBlog/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="杨雨翔"><meta itemprop="description" content=""><meta itemprop="image" content="https://gitee.com/yang_yu_xiang/BlogImages/raw/master/img/psb.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Yang's Blog"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Vue中的路由</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-28T16:16:41+08:00">2020-07-28 </time><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i> </span><span class="post-meta-item-text">更新于&#58;</span> <time title="更新于" itemprop="dateModified" datetime="2020-11-19T15:41:11+08:00">2020-11-19 </time></span><span class="post-category"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-folder-o"></i> </span><span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/MyBlog/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span> </a></span>， <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/MyBlog/categories/%E5%89%8D%E7%AB%AF/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span> </a></span></span><span class="post-comments-count"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-comment-o"></i> </span><a href="/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/" itemprop="commentCount"></span> </a></span><span class="post-meta-divider">|</span> <span class="page-pv">本文总阅读数 <i class="fa fa-file-o"></i> <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次</span><div class="post-wordcount"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i> </span><span class="post-meta-item-text">字数统计&#58;</span> <span title="字数统计">2.7k </span><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-clock-o"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span title="阅读时长">11</span></div></div></header><div class="post-body" itemprop="articleBody"><h1 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h1><h2 id="后端路由"><a href="#后端路由" class="headerlink" title="后端路由"></a>后端路由</h2><ul><li>概念:根据不同的用户URL请求，返回不同的内容</li><li>本质:URL请求地址与服务器资源之间的对应关系<h2 id="前端路由"><a href="#前端路由" class="headerlink" title="前端路由"></a>前端路由</h2></li><li>概念:根据不同的用户事件，显示不同的页面内容</li><li>本质:用户事件与事件处理函数之间的对应关系</li></ul><h1 id="Vue-Router"><a href="#Vue-Router" class="headerlink" title="Vue Router"></a>Vue Router</h1><p>&emsp;&emsp;vue Router(官网: <a href="https://router.vuejs.org/zh/" target="_blank" rel="noopener">https://router.vuejs.org/zh/</a> )是Vue.js官方的路由管理器。</p><a id="more"></a><h2 id="基本使用步骤"><a href="#基本使用步骤" class="headerlink" title="基本使用步骤"></a>基本使用步骤</h2><ul><li>1.引入相关的库文件</li><li>2.添加路由链接</li><li>3.添加路由填充位</li><li>4.定义路由组件</li><li>5.配置路由规则并创建路由实例</li><li>6.把路由挂载到Vue根实例中</li></ul><p>我们来看最简单的例子</p><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 被vm实例所控制的区域--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">" /user"</span>&gt;</span>User<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/register"</span>&gt;</span>Register<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--路由占位符--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义路由组件</span></span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">    template: <span class="string">'&lt;h1&gt;User 组件&lt;/h1&gt;'</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> Register = &#123;</span><br><span class="line">    template: <span class="string">'&lt;h1&gt;Register 组件&lt;/h1&gt;'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//创建路由实例对象</span></span><br><span class="line"><span class="keyword">var</span> router = <span class="keyword">new</span> vueRouter (&#123;</span><br><span class="line">    <span class="comment">// routes是路由规则数组</span></span><br><span class="line">    routes: [</span><br><span class="line">    <span class="comment">//每个路由规则都是一个配置对象，其中至少包含path和component两个属性:</span></span><br><span class="line">    <span class="comment">//path表示当前路由规则匹配的hash地址</span></span><br><span class="line">    <span class="comment">// component表示当前路由规则对应要展示的组件</span></span><br><span class="line">    &#123;<span class="attr">path</span>:<span class="string">'/user'</span>, <span class="attr">component</span>: User&#125;,</span><br><span class="line">    &#123;<span class="attr">path</span>:<span class="string">'/register'</span>,<span class="attr">component</span>: Register&#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//把路由挂载到Vue根实例中</span></span><br><span class="line"><span class="comment">//创建vm实例对象</span></span><br><span class="line"><span class="keyword">const</span> vm = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">    <span class="comment">//指定控制的区域</span></span><br><span class="line">    el: <span class="string">'#app'</span>，</span><br><span class="line">    data:&#123;&#125;</span><br><span class="line">    <span class="comment">//挂载路由实例对象</span></span><br><span class="line">    <span class="comment">// router: router  可简写</span></span><br><span class="line">    router</span><br><span class="line">)&#125;</span><br></pre></td></tr></table></figure><h2 id="路由重定向"><a href="#路由重定向" class="headerlink" title="路由重定向"></a>路由重定向</h2><p>路由重定向指的是∶用户在访问地址A的时候，强制用户跳转到地址c，从而展示特定的组件页面;<br>通过路由规则的<code>redirect</code>属性，指定一个新的路由地址，可以很方便地设置路由的重定向:</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> router = <span class="keyword">new</span> vueRouter (&#123;</span><br><span class="line">    routes: [</span><br><span class="line">        <span class="comment">//其中，path表示需要被重定向的原地址，redirect表示将要被重定向到的新地址</span></span><br><span class="line">        &#123;<span class="attr">path</span>:<span class="string">'/'</span>, <span class="attr">redirect</span>: <span class="string">'/user'</span>&#125;，</span><br><span class="line">        &#123;<span class="attr">path</span>:<span class="string">'/user'</span>, <span class="attr">component</span>: user&#125;,</span><br><span class="line">        &#123;<span class="attr">path</span>:<span class="string">'/ register'</span>, <span class="attr">component</span>: Register&#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><h2 id="嵌套路由"><a href="#嵌套路由" class="headerlink" title="嵌套路由"></a>嵌套路由</h2><p>嵌套路由功能分析</p><ul><li>点击父级路由链接显示模板内容</li><li>模板内容中又有子级路由链接</li><li>点击子级路由链接显示子级模板内容</li></ul><p>如图<br><img src="https://gitee.com/yang_yu_xiang/BlogImages/raw/master/img/%E5%B5%8C%E5%A5%97%E8%B7%AF%E7%94%B1.png" alt=""></p><h3 id="父路由组件模板"><a href="#父路由组件模板" class="headerlink" title="父路由组件模板"></a>父路由组件模板</h3><ul><li>父级路由链接</li><li>父组件路由填充位<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/user"</span>&gt;</span>User<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">routir-link</span> <span class="attr">to</span>=<span class="string">"/register"</span>&gt;</span>Register<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--控制组件的显示位置--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure></li></ul><h3 id="子级路由模板"><a href="#子级路由模板" class="headerlink" title="子级路由模板"></a>子级路由模板</h3><ul><li>子级路由链接</li><li>子级路由填充位<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Register =&#123;</span><br><span class="line">    template: <span class="string">`&lt;div&gt;</span></span><br><span class="line"><span class="string">    &lt;h1&gt;Register组件&lt;/h1&gt;</span></span><br><span class="line"><span class="string">    &lt;hr/&gt;</span></span><br><span class="line"><span class="string">    &lt;router-link to=" /register/tab1" &gt;Tab1&lt;/router-link&gt;</span></span><br><span class="line"><span class="string">    &lt;router-link to=" /register/tab2" &gt;Tab2&lt;/router-link&gt;</span></span><br><span class="line"><span class="string">    &lt;!--子路由填充位置 --&gt;</span></span><br><span class="line"><span class="string">    &lt;router-view /&gt;</span></span><br><span class="line"><span class="string">    &lt;/ div&gt;`</span></span><br><span class="line">&#125;</span><br><span class="line">corst Tab1 = &#123;</span><br><span class="line">    template: <span class="string">'&lt;h3&gt;tab1子组件&lt;/h3&gt;'</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> Tab2 = &#123;</span><br><span class="line">    template: <span class="string">'&lt;h3&gt;tab2子组件&lt;/h3&gt;'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li></ul><h3 id="嵌套路由配置"><a href="#嵌套路由配置" class="headerlink" title="嵌套路由配置"></a>嵌套路由配置</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ------------------第一种配置方法----------------------------</span></span><br><span class="line"><span class="comment">//父级路由通过children属性配置子级路由</span></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> vueRouter ([</span><br><span class="line">    routes:[</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">'/user'</span>, <span class="attr">component</span>: User &#125;,</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">'/register'</span>,<span class="attr">component</span>: Register,</span><br><span class="line">    children:[</span><br><span class="line">        &#123; <span class="attr">path</span>: <span class="string">'/register/tab1'</span>, <span class="attr">component</span>: Tab1 &#125;，</span><br><span class="line">        &#123; <span class="attr">path</span>: <span class="string">'/register/tab2'</span>, <span class="attr">component</span>: Tab2 &#125;</span><br><span class="line">    ]&#125;</span><br><span class="line">&#125;) <span class="comment">//通过children属性，为/register添加子路由规则</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//-------------------第二种配置方法-----------------------------</span></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  routes: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">'/user/:id'</span>, <span class="attr">component</span>: User,</span><br><span class="line">      children: [</span><br><span class="line">        <span class="comment">// 当 /user/:id/profile 匹配成功，</span></span><br><span class="line">        <span class="comment">// UserProfile 会被渲染在 User 的 &lt;router-view&gt; 中</span></span><br><span class="line">        &#123; <span class="attr">path</span>: <span class="string">'profile'</span>, <span class="attr">component</span>: UserProfile&#125;,</span><br><span class="line">        <span class="comment">// 当 /user/:id/posts 匹配成功</span></span><br><span class="line">        <span class="comment">// UserPosts 会被渲染在 User 的 &lt;router-view&gt; 中</span></span><br><span class="line">        &#123; <span class="attr">path</span>: <span class="string">'posts'</span>,<span class="attr">component</span>: UserPosts&#125;</span><br><span class="line">      ]</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><p><strong>要注意，以 / 开头的嵌套路径会被当作根路径。 这让你充分的使用嵌套组件而无须设置嵌套的路径。</strong></p><h2 id="动态路由匹配"><a href="#动态路由匹配" class="headerlink" title="动态路由匹配"></a>动态路由匹配</h2><p>应用场景:通过动态路由参数的模式进行路由匹配</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> router = <span class="keyword">new</span> vueRouter(&#123;</span><br><span class="line">    routes: [</span><br><span class="line">    <span class="comment">//动态路径参数以冒号开头</span></span><br><span class="line">    path:&#123;<span class="string">'/user/:id'</span>, <span class="attr">component</span>: user &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">    <span class="comment">//路由组件中通过$route.params获取路由参数</span></span><br><span class="line">    template: <span class="string">'&lt;div&gt;user的id为：&#123;&#123; $route.params.id &#125;&#125;&lt;/div&gt;'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="路由传参"><a href="#路由传参" class="headerlink" title="路由传参"></a>路由传参</h2><h3 id="最简单的路由传参方法"><a href="#最简单的路由传参方法" class="headerlink" title="最简单的路由传参方法"></a>最简单的路由传参方法</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 定义一个路由参数 --&gt;</span></span><br><span class="line">&#123; path: '/user/:id'&#125; </span><br><span class="line"><span class="comment">&lt;!-- 传值 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/user/123"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 取值 --&gt;</span></span><br><span class="line">this.$route.params.id </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- query传值,指通过?后面的拼接参数传值 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/user?id=123"</span>&gt;</span><span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 取值 --&gt;</span></span><br><span class="line">this.$route.query.id</span><br></pre></td></tr></table></figure><h3 id="利用props"><a href="#利用props" class="headerlink" title="利用props"></a>利用props</h3><p>&emsp;&emsp;刚刚说了利用动态路由匹配可以进行路由的传参，但是$route与对应路由形成高度耦合，不够灵活，所以可以使用<code>props</code>将组件和路由解耦</p><h3 id="props的值为布尔类型"><a href="#props的值为布尔类型" class="headerlink" title="props的值为布尔类型"></a>props的值为布尔类型</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> vueRouter (&#123;</span><br><span class="line">    routes: [</span><br><span class="line">        <span class="comment">//如果props被设置为true，route.params将会被设置为组件属性</span></span><br><span class="line">        &#123; <span class="attr">path</span>: <span class="string">'/user/:id'</span>,<span class="attr">component</span>: User, <span class="attr">props</span>: <span class="literal">true</span> &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">    props: [<span class="string">'id'</span>],<span class="comment">//使用props接收路由参数,就不需要通过$route.params</span></span><br><span class="line">    template: <span class="string">'&lt;div&gt;用户ID:&#123;&#123; id &#125;&#125;&lt;/div&gt;'</span><span class="comment">//使用路由参数</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="2-props的值为对象类型"><a href="#2-props的值为对象类型" class="headerlink" title="2.props的值为对象类型"></a>2.props的值为对象类型</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> vueRouter ( &#123;</span><br><span class="line">    routes: [</span><br><span class="line">    <span class="comment">//如果props是一个对象，它会被按原样设置为组件属性</span></span><br><span class="line">    ( path: <span class="string">'/user/:id'</span>,<span class="attr">component</span>: User,<span class="attr">props</span>: &#123; <span class="attr">uname</span>: <span class="string">'lisi'</span>，age: <span class="number">12</span> &#125;&#125;<span class="comment">//此时，无法访问id的值</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">    props:[<span class="string">'uname '</span>, <span class="string">'age'</span> ],</span><br><span class="line">    template: <span class="string">'&lt;div&gt;用户信息:&#123; uname + '</span>---<span class="string">' + age&#125;&#125;&lt;/div&gt;'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="props的值为函数类型"><a href="#props的值为函数类型" class="headerlink" title="props的值为函数类型"></a>props的值为函数类型</h3><p>我们现在又想获取id的值，又想获取name和age，怎么办呢</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">constrouter =<span class="keyword">new</span> vueRouter (&#123;</span><br><span class="line">    routes: [</span><br><span class="line">        <span class="comment">//如果props 是一个函数，则这个函数接收route对象为自己的形参</span></span><br><span class="line">        &#123;<span class="attr">path</span>:<span class="string">'/user/ :id'</span>,</span><br><span class="line">        component: User,</span><br><span class="line">        <span class="comment">//route为动态参数对象。在路由url后面有几个参数项，route里就有几个参数值</span></span><br><span class="line">        props: <span class="function"><span class="params">route</span> =&gt;</span>([ uname: <span class="string">'zs'</span>，age: <span class="number">20</span>,<span class="attr">id</span>: route.params.id &#125;)&#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">    props:[ <span class="string">'uname '</span>, <span class="string">'age'</span>, <span class="string">'id'</span>]，</span><br><span class="line">    template: <span class="string">'div&gt;用户信息:[&#123; uname + '</span>---<span class="string">' + age + '</span>---<span class="string">' + id]]&lt;/div&gt;'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="命名路由"><a href="#命名路由" class="headerlink" title="命名路由"></a>命名路由</h2><p>有时候，通过一个名称来标识一个路由显得更方便一些，特别是在链接一个路由，或者是执行一些跳转的时候。你可以在创建 <code>Router</code> 实例的时候，在 <code>routes</code> 配置中给某个路由设置名称。</p><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- &lt;router-link to="/user"&gt;User&lt;/router-link&gt; 传统路由 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">routir-link</span> <span class="attr">:to</span>=<span class="string">"&#123;name:'user',params:&#123;id:3&#125;&#125;"</span>&gt;</span>Register<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- name:路由名称  params:路由需要携带的参数 --&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--控制组件的显示位置--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">constrouter =<span class="keyword">new</span> vueRouter (&#123;</span><br><span class="line">    routes: [</span><br><span class="line">        <span class="comment">//如果props 是一个函数，则这个函数接收route对象为自己的形参</span></span><br><span class="line">        &#123;   </span><br><span class="line">            name:<span class="string">'user'</span><span class="comment">//**给路由起一个名字**</span></span><br><span class="line">            path:<span class="string">'/user/ :id'</span>,</span><br><span class="line">            component: User,</span><br><span class="line">            <span class="comment">//route为动态参数对象。在路由url后面有几个参数项，route里就有几个参数值</span></span><br><span class="line">            props: <span class="function"><span class="params">route</span> =&gt;</span>([ uname: <span class="string">'zs'</span>，age: <span class="number">20</span>,<span class="attr">id</span>: route.params.id &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">    props:[ <span class="string">'uname '</span>, <span class="string">'age'</span>, <span class="string">'id'</span>]，</span><br><span class="line">    template: <span class="string">'&lt;div&gt;用户信息:&#123;&#123; uname + '</span>---<span class="string">' + age + '</span>---<span class="string">' + id&#125;&#125;&lt;/div&gt;'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h1 id="路由的编程式导航"><a href="#路由的编程式导航" class="headerlink" title="路由的编程式导航"></a>路由的编程式导航</h1><h2 id="页面导航的两种方式："><a href="#页面导航的两种方式：" class="headerlink" title="页面导航的两种方式："></a>页面导航的两种方式：</h2><ul><li><p>声明式导航:通过点击链接实现导航的方式，叫做声明式导航<br>例如:普通网页中的<a></a>链接或vue中的<router-link></router-link></p></li><li><p>编程式导航:通过调用JavaScript形式的API实现导航的方式，叫做编程式导航<br>例如:普通网页中的location.href<br>心</p></li></ul><h2 id="编程式导航基本用法"><a href="#编程式导航基本用法" class="headerlink" title="编程式导航基本用法"></a>编程式导航基本用法</h2><p>常用的编程式导航API如下:</p><ul><li>this.$router.push(‘hash地址’)</li><li>this.$router.replace(‘hash地址’)</li><li>this.$router.go(n)<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//push的用法</span></span><br><span class="line"><span class="keyword">const</span> User = &#123;</span><br><span class="line">    template: <span class="string">`&lt;div&gt;</span></span><br><span class="line"><span class="string">        &lt;button @click="goRegister"&gt;跳转到注册页面&lt;/button&gt;</span></span><br><span class="line"><span class="string">    &lt;/div&gt;`</span>,</span><br><span class="line">    methods:&#123;</span><br><span class="line">    goRegister: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//用编程的方式控制路由跳转</span></span><br><span class="line">    <span class="keyword">this</span>.$router.push(<span class="string">'/register'</span> );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//replace的用法</span></span><br><span class="line"><span class="comment">//跟 router.push 很像，唯一的不同就是，它不会向 history 添加新记录，而是跟它的方法名一样 —— 替换掉当前的 history 记录。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//go的用法</span></span><br><span class="line"><span class="keyword">const</span> Register = &#123;</span><br><span class="line">    template: <span class="string">`&lt;div&gt;</span></span><br><span class="line"><span class="string">        &lt;h1&gt;Register组件&lt;/h1&gt;</span></span><br><span class="line"><span class="string">        &lt;button @click="goBack"&gt;后退&lt;/button&gt;</span></span><br><span class="line"><span class="string">    &lt;/div&gt;`</span>,</span><br><span class="line">    methods: &#123;</span><br><span class="line">        goBack()&#123;</span><br><span class="line">            <span class="keyword">this</span>.$router.go(<span class="number">-1</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><code>$router.push({path:&#39;&#39;})</code>本质是向history栈中添加一个路由，在我们看来是 切换路由，但本质是在添加一个<code>history</code>记录<h2 id="编程式导航的参数规则"><a href="#编程式导航的参数规则" class="headerlink" title="编程式导航的参数规则"></a>编程式导航的参数规则</h2><code>router.push()</code>方法的参数规则<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//字符串(路径名称)</span></span><br><span class="line">router.push( <span class="string">'/home'</span>)</span><br><span class="line"><span class="comment">//对象</span></span><br><span class="line">router.push( &#123; <span class="attr">path</span>: <span class="string">'/home'</span> &#125;)</span><br><span class="line"><span class="comment">//命名的路由(传递参数)</span></span><br><span class="line">router.push(&#123; <span class="attr">name</span>: <span class="string">'/user'</span>, <span class="attr">params</span>: &#123; <span class="attr">userId</span>: <span class="number">123</span> &#125;&#125;)</span><br><span class="line"><span class="comment">//带查询参数，变成/register?uname=lisi</span></span><br><span class="line">router.push( &#123; <span class="attr">path</span>: <span class="string">'/register'</span>, <span class="attr">query</span>: &#123; <span class="attr">uname</span>: <span class="string">'lisi'</span> &#125;&#125;)</span><br></pre></td></tr></table></figure></li></ul><h1 id="hash和history"><a href="#hash和history" class="headerlink" title="hash和history"></a>hash和history</h1><h2 id="hash"><a href="#hash" class="headerlink" title="hash"></a>hash</h2><ul><li><p>hash 虽然出现在 URL 中，但不会被包括在 HTTP 请求中，对后端完全没有影- 响，因此改变 hash 不会重新加载页面。</p></li><li><p>hash 模式下，仅 hash 符号之前的内容会被包含在请求中，如 <a href="http://www.-" target="_blank" rel="noopener">http://www.-</a> npc.com，因此对于后端来说，即使没有做到对路由的全覆盖，也不会返回 - 404 错误。</p></li><li><p>hash 设置的新值必须与原来不一样才会触发动作将记录添加到栈中。</p></li><li><p>hash 只可修改 # 后面的部分，因此只能设置与当前 URL 同文档的 URL。</p></li><li><p>hash 只可添加短字符串。</p><h2 id="history（服务器环境下才有效果）"><a href="#history（服务器环境下才有效果）" class="headerlink" title="history（服务器环境下才有效果）"></a>history（服务器环境下才有效果）</h2></li><li><p>pushState() 设置的新 URL 可以是与当前 URL 同源的任意 URL；；</p></li><li><p>pushState() 设置的新 URL 可以与当前 URL 一模一样，这样也会把记添加到栈中；</p></li><li><p>pushState() 通过 stateObject 参数可以添加任意类型的数据到记中；；</p></li><li><p>pushState() 可额外设置 title 属性供后续使用。</p></li></ul><h1 id="路由导航守卫"><a href="#路由导航守卫" class="headerlink" title="路由导航守卫"></a>路由导航守卫</h1><h2 id="全局守卫"><a href="#全局守卫" class="headerlink" title="全局守卫"></a>全局守卫</h2><p>路由导航守卫可以用于在前端路由跳转之前判断用户的登录状态。写一个vue_shop中的例子：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//在router.js实例中 挂载一个全局路由导航守卫</span></span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to，<span class="keyword">from</span>,next</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="comment">// to 将要访问的路径</span></span><br><span class="line">    <span class="comment">// from 代表从哪个路径跳转而来</span></span><br><span class="line">    <span class="comment">// next是一个函数，表示放行</span></span><br><span class="line">    <span class="comment">//next()放行next( '/login'）强制跳转</span></span><br><span class="line">    <span class="keyword">if</span> (to.path === <span class="string">'/login'</span>) <span class="keyword">return</span> next()</span><br><span class="line">    <span class="comment">//获取token</span></span><br><span class="line">    <span class="keyword">const</span> tokenStr = <span class="built_in">window</span>.sessionStorage.getItem(<span class="string">"token"</span>)</span><br><span class="line">    <span class="comment">//不存在token，返回登录页</span></span><br><span class="line">    <span class="keyword">if</span> (!tokenstr) <span class="keyword">return</span> next(<span class="string">'/login'</span>)</span><br><span class="line">    <span class="comment">//验证通过，放行</span></span><br><span class="line">    next()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><p><strong>确保 <code>next</code> 函数在任何给定的导航守卫中都被严格调用一次。它可以出现多于一次，但是只能在所有的逻辑路径都不重叠的情况下，否则钩子永远都不会被解析或报错。</strong>这里有一个在用户未能验证身份时重定向到 /login 的示例：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (to.name !== <span class="string">'Login'</span> &amp;&amp; !isAuthenticated) next(&#123; <span class="attr">name</span>: <span class="string">'Login'</span> &#125;)</span><br><span class="line">  <span class="keyword">else</span> next()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure><h2 id="路由独享守卫"><a href="#路由独享守卫" class="headerlink" title="路由独享守卫"></a>路由独享守卫</h2><p>可以在路由配置上直接定义 <code>beforeEnter</code> 守卫：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123;</span><br><span class="line">  routes: [</span><br><span class="line">    &#123; <span class="attr">path</span>: <span class="string">'/foo'</span>,<span class="attr">component</span>: Foo,</span><br><span class="line">      beforeEnter: <span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></div><div><div class="my_post_copyright"><script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script><script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script><script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script><p><span>本文标题:</span><a href="/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/">Vue中的路由</a></p><p><span>文章作者:</span><a href="/" title="访问 杨雨翔 的个人博客">杨雨翔</a></p><p><span>发布时间:</span>2020年07月28日 - 16:16</p><p><span>最后更新:</span>2020年11月19日 - 15:41</p><p><span>原始链接:</span><a href="/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/" title="Vue中的路由">https://gitee.com/yang_yu_xiang/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/</a> <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://gitee.com/yang_yu_xiang/MyBlog/2020/07/28/Vue%E4%B8%AD%E7%9A%84%E8%B7%AF%E7%94%B1/" aria-label="复制成功！"></i></span></p><p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p></div><script>var clipboard=new Clipboard(".fa-clipboard");$(".fa-clipboard").click((function(){clipboard.on("success",(function(){swal({title:"",text:"复制成功",icon:"success",showConfirmButton:!0})}))}))</script></div><div style="text-align:center;color:#ccc;font-size:16px">---------------- The End ----------------</div><footer class="post-footer"><div class="post-tags"><a href="/MyBlog/tags/Vue/" rel="tag"><i class="fa fa-tag"></i> Vue</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/MyBlog/2020/07/26/Vue%E4%B8%AD%E7%88%B6%E5%AD%90%E7%BB%84%E4%BB%B6%E4%BC%A0%E5%80%BC/" rel="next" title="Vue中父子组件传值和访问"><i class="fa fa-chevron-left"></i> Vue中父子组件传值和访问</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/MyBlog/2020/07/28/Vue%E8%B7%AF%E7%94%B1%E4%BC%A0%E5%8F%82param%E4%B8%8Equery%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F%E7%9A%84%E5%8C%BA%E5%88%AB/" rel="prev" title="Vue路由传参param与query两种方式的区别">Vue路由传参param与query两种方式的区别 <i class="fa fa-chevron-right"></i></a></div></div></footer></div></article><div class="post-spread"><div class="jiathis_style"><span class="jiathis_txt">分享到：</span> <a class="jiathis_button_fav">收藏夹</a> <a class="jiathis_button_copy">复制网址</a> <a class="jiathis_button_email">邮件</a> <a class="jiathis_button_weixin">微信</a> <a class="jiathis_button_qzone">QQ空间</a> <a class="jiathis_button_tqq">腾讯微博</a> <a class="jiathis_button_douban">豆瓣</a> <a class="jiathis_button_share">一键分享</a> <a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a> <a class="jiathis_counter_style"></a></div><script type="text/javascript">var jiathis_config={data_track_clickback:!0,summary:"",shortUrl:!1,hideMore:!1}</script><script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script></div></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div id="sidebar-dimmer"></div><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap">站点概览</li></ul><section class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><img class="site-author-image" itemprop="image" src="https://gitee.com/yang_yu_xiang/BlogImages/raw/master/img/psb.jpg" alt="杨雨翔"><p class="site-author-name" itemprop="name">杨雨翔</p><p class="site-description motion-element" itemprop="description"></p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"><a href="/MyBlog/archives/"><span class="site-state-item-count">53</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"><a href="/MyBlog/categories/index.html"><span class="site-state-item-count">12</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"><a href="/MyBlog/tags/index.html"><span class="site-state-item-count">32</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://gitee.com/yang_yu_xiang" target="_blank" title="码云"><i class="fa fa-fw fa-git"></i>码云</a> </span><span class="links-of-author-item"><a href="http://wpa.qq.com/msgrd?v=3&uin=1372201820&site=qq&menu=yes" target="_blank" title="QQ"><i class="fa fa-fw fa-qq"></i>QQ</a> </span><span class="links-of-author-item"><a href="https://github.com/gezhicui" target="_blank" title="Github"><i class="fa fa-fw fa-github"></i>Github</a> </span><span class="links-of-author-item"><a href="mailto:1372201820@qq.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a></span></div><div class="links-of-blogroll motion-element links-of-blogroll-block"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> 友情链接</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><a href="https://cloudhao.top/#/search/%E5%9F%9F%E5%90%8D" title="陈昀昊的小窝" target="_blank">陈昀昊的小窝</a></li><li class="links-of-blogroll-item"><a href="http://www.shezhiwei.top/" title="佘智伟的博客" target="_blank">佘智伟的博客</a></li><li class="links-of-blogroll-item"><a href="https://blog.csdn.net/qq_43185206" title="阿呆的小鸡仔" target="_blank">阿呆的小鸡仔</a></li></ul></div></div></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#路由"><span class="nav-number">1.</span> <span class="nav-text">路由</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#后端路由"><span class="nav-number">1.1.</span> <span class="nav-text">后端路由</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#前端路由"><span class="nav-number">1.2.</span> <span class="nav-text">前端路由</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vue-Router"><span class="nav-number">2.</span> <span class="nav-text">Vue Router</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#基本使用步骤"><span class="nav-number">2.1.</span> <span class="nav-text">基本使用步骤</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#路由重定向"><span class="nav-number">2.2.</span> <span class="nav-text">路由重定向</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#嵌套路由"><span class="nav-number">2.3.</span> <span class="nav-text">嵌套路由</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#父路由组件模板"><span class="nav-number">2.3.1.</span> <span class="nav-text">父路由组件模板</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#子级路由模板"><span class="nav-number">2.3.2.</span> <span class="nav-text">子级路由模板</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#嵌套路由配置"><span class="nav-number">2.3.3.</span> <span class="nav-text">嵌套路由配置</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#动态路由匹配"><span class="nav-number">2.4.</span> <span class="nav-text">动态路由匹配</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#路由传参"><span class="nav-number">2.5.</span> <span class="nav-text">路由传参</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#最简单的路由传参方法"><span class="nav-number">2.5.1.</span> <span class="nav-text">最简单的路由传参方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#利用props"><span class="nav-number">2.5.2.</span> <span class="nav-text">利用props</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#props的值为布尔类型"><span class="nav-number">2.5.3.</span> <span class="nav-text">props的值为布尔类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-props的值为对象类型"><span class="nav-number">2.5.4.</span> <span class="nav-text">2.props的值为对象类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#props的值为函数类型"><span class="nav-number">2.5.5.</span> <span class="nav-text">props的值为函数类型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#命名路由"><span class="nav-number">2.6.</span> <span class="nav-text">命名路由</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#路由的编程式导航"><span class="nav-number">3.</span> <span class="nav-text">路由的编程式导航</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#页面导航的两种方式："><span class="nav-number">3.1.</span> <span class="nav-text">页面导航的两种方式：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#编程式导航基本用法"><span class="nav-number">3.2.</span> <span class="nav-text">编程式导航基本用法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#编程式导航的参数规则"><span class="nav-number">3.3.</span> <span class="nav-text">编程式导航的参数规则</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#hash和history"><span class="nav-number">4.</span> <span class="nav-text">hash和history</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#hash"><span class="nav-number">4.1.</span> <span class="nav-text">hash</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#history（服务器环境下才有效果）"><span class="nav-number">4.2.</span> <span class="nav-text">history（服务器环境下才有效果）</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#路由导航守卫"><span class="nav-number">5.</span> <span class="nav-text">路由导航守卫</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#全局守卫"><span class="nav-number">5.1.</span> <span class="nav-text">全局守卫</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#路由独享守卫"><span class="nav-number">5.2.</span> <span class="nav-text">路由独享守卫</span></a></li></ol></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2021</span> <span class="with-love"><i class="fa fa-send"></i> </span><span class="author" itemprop="copyrightHolder">杨雨翔</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-area-chart"></i> </span><span class="post-meta-item-text">站点总字数&#58;</span> <span title="站点总字数">61.9k</span></div><div class="busuanzi-count"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="site-uv">本站访问数 <i class="fa fa-user"></i> <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> 人次 </span><span class="site-pv">本站总访问量 <i class="fa fa-eye"></i> <span class="busuanzi-value" id="busuanzi_value_site_pv"></span> 次</span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span id="scrollpercent"><span>0</span>%</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/MyBlog/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/MyBlog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/MyBlog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/MyBlog/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/MyBlog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/MyBlog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script><script type="text/javascript" src="/MyBlog/js/src/utils.js?v=5.1.4"></script><script type="text/javascript" src="/MyBlog/js/src/motion.js?v=5.1.4"></script><script type="text/javascript" src="/MyBlog/js/src/affix.js?v=5.1.4"></script><script type="text/javascript" src="/MyBlog/js/src/schemes/pisces.js?v=5.1.4"></script><script type="text/javascript" src="/MyBlog/js/src/scrollspy.js?v=5.1.4"></script><script type="text/javascript" src="/MyBlog/js/src/post-details.js?v=5.1.4"></script><script type="text/javascript" src="/MyBlog/js/src/bootstrap.js?v=5.1.4"></script><script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="//unpkg.com/valine/dist/Valine.min.js"></script><script type="text/javascript">var GUEST=["nick","mail","link"],guest="nick";guest=guest.split(",").filter(e=>GUEST.indexOf(e)>-1),new Valine({el:"#comments",verify:!1,notify:!1,appId:"i5Tl5zN4f4LxoJgipanUuaml-gzGzoHsz",appKey:"wqw6uYNCQkeVxBffKebM29NH",placeholder:"说点什么吧...",avatar:"mm",guest_info:guest,pageSize:"10"})</script><script type="text/javascript">var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":/json$/i.test(search_path)&&(isXml=!1);var path="/MyBlog/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")};function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map((function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}})).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach((function(n){var r=!1,s=0,a=0,i=n.title.trim(),c=i.toLowerCase(),l=n.content.trim().replace(/<[^>]+>/g,""),h=l.toLowerCase(),p=decodeURIComponent(n.url),u=[],f=[];if(""!=i&&(e.forEach((function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}u=u.concat(e(t,c,!1)),f=f.concat(e(t,h,!1))})),(u.length>0||f.length>0)&&(r=!0,s=u.length+f.length)),r){function d(e,o,n,r){for(var s=r[r.length-1],i=s.position,c=s.word,l=[],h=0;i+c.length<=n&&0!=r.length;){c===t&&h++,l.push({position:i,length:c.length});var p=i+c.length;for(r.pop();0!=r.length&&(i=(s=r[r.length-1]).position,c=s.word,p>i);)r.pop()}return a+=h,{hits:l,start:o,end:n,searchTextCount:h}}[u,f].forEach((function(t){t.sort((function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length}))}));var g=[];0!=u.length&&g.push(d(0,0,i.length,u));for(var v=[];0!=f.length;){var $=f[f.length-1],C=$.position,m=$.word,x=C-20,w=C+80;x<0&&(x=0),w<C+m.length&&(w=C+m.length),w>l.length&&(w=l.length),v.push(d(0,x,w,f))}v.sort((function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start}));var y=parseInt("1");function T(t,e){var o="",n=e.start;return e.hits.forEach((function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r})),o+=t.substring(n,e.end)}y>=0&&(v=v.slice(0,y));var b="";0!=g.length?b+="<li><a href='"+p+"' class='search-result-title'>"+T(i,g[0])+"</a>":b+="<li><a href='"+p+"' class='search-result-title'>"+i+"</a>",v.forEach((function(t){b+="<a href='"+p+'\'><p class="search-result">'+T(l,t)+"...</p></a>"})),b+="</li>",o.push({item:b,searchTextCount:a,hitCount:s,id:o.length})}})),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort((function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id}));var a='<ul class="search-result-list">';o.forEach((function(t){a+=t.item})),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click((function(t){t.stopPropagation(),!1===isfetched?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()})),$(".popup-btn-close").click(onPopupClose),$(".popup").click((function(t){t.stopPropagation()})),$(document).on("keyup",(function(t){27===t.which&&$(".search-popup").is(":visible")&&onPopupClose()}))</script><script src="/MyBlog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/MyBlog/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":false},"log":false});</script></body></html>